define([
    'jquery',
    "signin",
    "layui",
    'jquery-cookie',

], function ($, signin, layui) {

    //菜单栏切换
    function meneTab() {
        $(".menu  .menu_wrap").on("click", "dl dt", function () {
            $(this).siblings("dd").css("display", "block").parent().siblings().children("dd").css("display", "none");
        });

        $(".menu  .menu_wrap").on("click", "dl dd", function () {
            $(this).removeClass("cur").addClass("cur").parent().siblings().children("dd").removeClass("cur");
            $(this).siblings().removeClass("cur");
            return false;
        });
    }

    //获取地区数据---获取指定城市的所有的下级
    function setLocation() {
        let baseUrl = signin.getBaseUrl();
        //加载省份数据
        $.get(baseUrl + "/system/province", {
                parentId: 1
            },
            function (res) {
                // console.log(res);
                $(".address_bd form ul").find("li #province").html('');
                res.data.forEach(item => {
                    let node = $(`<option value="${item.id}">${item.name}</option>
                    `);
                    $(".address_bd form ul").find("li #province").append(node);
                });
            });

        // 省份变化  加载城市数据
        $(".address_bd form ul").on("change", "#province", function () {
            let parentId = $(this).val();
            $.get(baseUrl + "/system/province", {
                    parentId: parentId
                },
                function (res) {
                    $(".address_bd form ul").find("li #city").html('');
                    res.data.forEach(function (item) {
                        let node = $(`<option value="${item.id}">${item.name}</option>
                        `);
                        $(".address_bd form ul").find("li #city").append(node);
                    });
                });
        });

        //城市变化  加载三级地区数据
        $(".address_bd form ul").on("change", "#city", function () {
            let parentId = $(this).val();
            $.get(baseUrl + "/system/province", {
                    parentId: parentId
                },
                function (res) {
                    $(".address_bd form ul").find("li #area").html('');
                    res.data.forEach(function (item) {
                        let node = $(`<option value="${item.id}">${item.name}</option>
                    `);
                        $(".address_bd form ul").find("li #area").append(node);
                    });
                });
        });
    }

    //新增地址
    function setNewAddress() {
        let baseUrl = signin.getBaseUrl();
        let userInfo = null;
        $.cookie("userInfo") == null ? '' : userInfo = JSON.parse($.cookie("userInfo"));
        // 设置隐藏域保存是否设置默认地址
        $('.isDefaultChange').on('click', function () {
            if ($(this).prop('checked')) {
                $('.isDefault').val(1); //确认设为默认地址
            } else {
                $('.isDefault').val(0); //不设为默认地址
            }
        });
        $('.btn').on('click', function () {
            let data = $('.add_address').serialize();
            console.log(data);
            data += '&userId=' + userInfo.id;
            $.post(baseUrl + '/address/add', data, function (res) {
                console.log(res);
                if (res.code != 1) {
                    // layer.load(2);
                    // location.reload();
                    getUserAddress();
                }
            });
            return false;
        });


    }

    //加载用户已经添加过的地址
    function getUserAddress() {
        let baseUrl = signin.getBaseUrl();
        let userInfo = null;
        $.cookie("userInfo") == null ? '' : userInfo = JSON.parse($.cookie("userInfo"));
        $.get(baseUrl + "/address/lists", {
                userId: userInfo.id
            },
            function (res) {
                // console.log(res);
                $(".content .address_hd").find("form").html('');
                for (let i = 0; i < res.data.length; i++) {
                    node = $(`
                    <dl data-addressId="${res.data[i].id}" class="${i==res.data.length-1?this.className="last":''}"}>
					<dt>${i+1}.<i name="consignee">${res.data[i].consignee}</i>&nbsp;&nbsp;
                            <i name="provinceName" data-provinceId="${res.data[i].province}"> ${res.data[i].provinceName}</i>&nbsp;&nbsp; 
                            <i name="cityName" data-cityId="${res.data[i].city}> ${res.data[i].cityName}</i> 
                            <i name="areaName" data-areaId="${res.data[i].area}> ${res.data[i].areaName}</i>
                            <i name="address" > ${res.data[i].address} </i>
                            <i name="mobile"  > ${res.data[i].mobile}  </i>
                     </dt>
					<dd>
						<a href="javascript:void(0);">修改</a>
						<a href="">删除</a>
						<a href="" style="color:${res.data[i].isDefault == 1 ? 'red' : ''}"  data-isDefault="${res.data[i].isDefault}">设为默认地址</a>
					</dd>
				</dl>
                    `);
                    // node.insertAfter($(".content .address_hd").find("h3"));
                    node.appendTo($(".content .address_hd").find("form"));
                }
            });
    }

    //修改地址
    function alterAddress() {
        let baseUrl = signin.getBaseUrl();
        let userInfo = null;
        $.cookie("userInfo") == null ? '' : userInfo = JSON.parse($.cookie("userInfo"));
        let userId = userInfo.id;
        $(".address_hd").on("click", " a", function () {
            let $this = $(this);
            let addressId = $this.parent("dd").parent("dl").attr("data-addressid");
            // console.log($this.index());
            if ($this.index() == 0) {
                // 修改地址
                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    area: ['auto'],
                    skin: 'address_bd',
                    content: `	<form action="" name="address_form" class="add_address">
					<ul>
						<li>
							<label for=""><span>*</span>收 货 人：</label>
							<input type="text" name="consignee" class="txt" />
						</li>
						<li>
							<label for=""><span>*</span>所在地区：</label>
							<select name="province" id="province">
								<option value="">请选择</option>

							</select>

							<select name="city" id="city">
								<option value="">请选择</option>
							</select>

							<select name="area" id="area">
								<option value="">请选择</option>
							</select>
						</li>
						<li>
							<label for=""><span>*</span>详细地址：</label>
							<input type="text" name="address" class="txt address" />
						</li>
						<li>
							<label for=""><span>*</span>手机号码：</label>
							<input type="text" name="mobile" class="txt" />
						</li>
						<li>
							<label for="">&nbsp;</label>
							<input type="hidden" name="isDefault" class="isDefault" value="0" />
							<input type="checkbox" class="check isDefaultChange" ${$(this).prop('checked')?$('.isDefault').val(1): $('.isDefault').val(0)}  />设为默认地址
						</li>
						<li>
							<label for="">&nbsp;</label>
						</li>
					</ul>
				</form>`,
                    btn: ['确定', '关闭'],
                    success: function (layero, index) {

                        setLocation();
                        $('.isDefaultChange').on('click', function () {
                            if ($(this).prop('checked')) {
                                $('.isDefault').val(1); //确认设为默认地址
                            } else {
                                $('.isDefault').val(0); //不设为默认地址
                            }
                        });
                    },
                    yes: function (index) {
                        let newData = $('.add_address').serialize();
                        // console.log(newData);
                        newData = "addressId=" + addressId + "&" + newData + "&userId=" + userId;
                        console.log(newData);
                        $.post(baseUrl + "/address/change", newData,
                            function (res) {
                                console.log(res);
                                layer.msg("修改成功");
                            });
                        //最后关闭弹出层
                        layer.close(index);
                    },
                });

            } else if ($this.index() == 1) {
                // 删除地址
                layer.open({
                    title: false,
                    closeBtn: 0,
                    content: '您确定要删除吗',
                    btn: ['确定', '关闭'],
                    yes: function () {
                        console.log(userId, addressId);
                        $.get(baseUrl + "/address/remove", {
                                addressId,
                                userId
                            },
                            function (res) {
                                layer.msg("删除成功");
                            });
                        getUserAddress();
                    }
                });
            } else {
                //设为默认地址
                let dataIsDefaultId = $this.attr("data-isdefault");
                dataIsDefaultId == 1 ? dataIsDefaultId = 0 : dataIsDefaultId = 1;
                console.log(dataIsDefaultId)
                new Promise(function (resolve, reject) {
                    $.get(baseUrl + "/address/detail", {
                            addressId,
                            userId
                        },
                        function (res) {
                            resolve(res.data)
                        });
                }).then(function (data) {
                    let newData = "addressId=" + addressId + "&consignee=" + data.consignee + "&mobile=" + data.mobile + "&province=" + data.province + "&city=" + data.city + "&area=" + data.area + "&address=" + data.address + "&isDefault=" + dataIsDefaultId + "&userId=" + userId;
                    $.post(baseUrl + "/address/change", newData,
                        function (res) {
                            console.log(res);
                            getUserAddress();
                        });
                    console.log(newData);
                });
            }

            return false;
        });




    }


    return {
        meneTab: meneTab,
        setLocation: setLocation,
        setNewAddress: setNewAddress,
        getUserAddress: getUserAddress,
        alterAddress: alterAddress
    }

});